/* eslint-disable no-shadow */
/* eslint-disable @typescript-eslint/no-unused-vars */
/**
 * 候选人，通知候选人
 */
import React, { useEffect, useState } from 'react';
import { Form, Card, Button, Input, Select, message, Spin, Icon as AntdIcon, Checkbox, Modal, Icon } from 'antd';
import { get as getPath } from 'object-path';
import BraftEditor from 'braft-editor';
import { customUpload } from '@/utils/fileUpload';
import { BottomAction } from '@/components';
import { useRequest, defaultFormatResult } from '@/hooks';
import FileUpload from '@/components/Custom/FileUpload';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import pageTabUtil from '@/utils/pageTabUtil';
import copy from 'copy-to-clipboard';
import { NOTICE_TYPE } from '../dictionary';
import {
    getCandidateInfo,
    getEmailNoticeTemplate,
    sendHireEmail,
    sendEmailNotice,
    sendEmailNoticeToThirdParty,
    getInterviewArrangeDetail,
    updateHomeWork
} from '../service';
import { getNoticeTemplateList } from '../Setting/service';
import { TEMPLATE_TYPE } from '../Setting/constants';
import { transformFileList } from '../utils';
import styles from './index.less';
import { UploadWork } from '../components';

const { Option } = Select;
const { confirm } = Modal;
// 为兼容旧参数，多做一层参数转发
const TYPE_MAPPING = {
    [NOTICE_TYPE.INVITE]: TEMPLATE_TYPE.INTERVIEW,
    [NOTICE_TYPE.WEED_OUT]: TEMPLATE_TYPE.ELIMINATE,
    [NOTICE_TYPE.TERMINATE]: TEMPLATE_TYPE.ELIMINATE,
    [NOTICE_TYPE.OFFER]: TEMPLATE_TYPE.OFFER,
    [NOTICE_TYPE.BACKGROUND]: TEMPLATE_TYPE.BACKGROUND
};

const EmailNotice = ({ form, location }) => {
    // 文件信息
    const [showFileList, setShowFileList] = useState([]);
    const { getFieldValue, setFieldsValue } = form;
    const [homeWork, setHomeWork] = React.useState({});
    const [templateList, setTemplateList] = React.useState([]);
    const { query } = location;
    const [interviewWay, setInterviewWay] = useState(0);
    const { candidateId, contactId, employId, noticeType = TEMPLATE_TYPE.INTERVIEW, backgroundId, email } = query;
    const { getFieldDecorator } = form;
    // 是否是特殊的三方背调
    const isBackground = !!backgroundId;
    const hasEmail = !!email;

    const { data: interviewArrangeDetail } = useRequest(
        () => {
            if (noticeType !== NOTICE_TYPE.OFFER) {
                return getInterviewArrangeDetail({ candidateId, contactId });
            }
            return Promise.resolve({ code: 10000, data: {} });
        },
        {
            ...defaultFormatResult,
            refreshDeps: [candidateId],
            initialData: {},
            ready: !backgroundId && !!contactId
        }
    );

    const { data: talentInfo, loading: talentLoading } = useRequest(() => getCandidateInfo(candidateId), {
        refreshDeps: [candidateId],
        initialData: {},
        ...defaultFormatResult
        // onSuccess: result => {
        //     if (!result.talentOriginalFileUrl) return;
        //     if (!isBackground) return;
        //     const fileList = [
        //         {
        //             keyName: 1,
        //             url: result.talentOriginalFileUrl,
        //             originName: `${result.talentName}的简历`
        //         }
        //     ];
        //     setFieldsValue({
        //         resourceRelation: transformFileList(fileList)
        //     });
        // }
    });

    const showUpdateTalentEmail = React.useMemo(
        () =>
            !isBackground &&
            [TEMPLATE_TYPE.OFFER, TEMPLATE_TYPE.INTERVIEW, NOTICE_TYPE.INVITE, NOTICE_TYPE.OFFER].indexOf(
                noticeType
            ) !== -1,
        [isBackground, noticeType]
    );

    // 获取模板列表
    const { data: allTemplateList, loading: templateLoading } = useRequest(
        () => getNoticeTemplateList({ templateCategory: 1, pageSize: 99999 }),
        {
            refreshDeps: [noticeType],
            initialData: [],
            formatResult: result => {
                const { code, data } = result;
                if (code === 10000) {
                    const { rows = [] } = data;
                    return rows;
                }
                return [];
            }
        }
    );

    const { companyCode } = talentInfo;
    useEffect(() => {
        // 所有模板数据请求成功后才执行
        if (allTemplateList && allTemplateList.length) {
            let res = allTemplateList.filter(item => item.templateType === (TYPE_MAPPING[noticeType] || noticeType));
            const isFilter = backgroundId || employId;
            // 录用/背调需要根据行政机构对数据进行过滤
            if (isFilter) {
                // 过滤出 companyCode === organizationCodes 的模板
                // 加入默认模板 isDefault === 1
                res = companyCode
                    ? res.filter(
                          item => item.organizationCodes.split(',').includes(companyCode) || item.isDefault === 1
                      )
                    : [];
                console.log('===============================================>', res);
                if (res.length > 1) {
                    for (let index = 0; index < res.length; index += 1) {
                        const item = res[index];
                        if (item.isDefault && index < res.length - 1) {
                            const temp = res[res.length - 1];
                            res[res.length - 1] = item;
                            res[index] = temp;
                            break;
                        }
                    }
                }
            }
            setTemplateList(res);
        }
    }, [allTemplateList, companyCode]);

    const changeAllFileList = showFileListReturn => {
        if (showFileListReturn.length <= 5) {
            console.log('showFileListReturn---', showFileListReturn);
            setShowFileList(showFileListReturn);
        } else {
            message.error('最多只能上传五个附件');
        }
    };

    const currentTemplateId = getFieldValue('templateId');

    const { data: templateData, loading } = useRequest(
        () => {
            if (currentTemplateId) {
                const extraParam = { backgroundId, employId, contactId, candidateId };
                const param = { templateId: currentTemplateId, ...extraParam };
                return getEmailNoticeTemplate(param);
            }
            return Promise.resolve({ code: 10000, data: {} });
        },
        {
            refreshDeps: [currentTemplateId, contactId, candidateId, employId],
            initialData: {},
            ...defaultFormatResult,
            onSuccess: result => {
                // if (isBackground) return;
                if (!result) {
                    setFieldsValue({
                        templateTitle: '',
                        templateContent: BraftEditor.createEditorState(''),
                        resourceRelation: transformFileList([])
                    });
                    return;
                }
                const { templateContent, templateTitle, fileVOS = [] } = result;
                if (templateContent || templateTitle) {
                    const oldFileList = showFileList;
                    if (fileVOS && fileVOS.length > 0) {
                        // 将邮件模板默认的附件添加进来
                        const fileArray = fileVOS.map(item => ({
                            uid: item.keyName,
                            name: item.originName,
                            status: 'done',
                            url: item.url,
                            response: item.url,
                            isDefault: true
                        }));
                        setShowFileList(oldFileList.concat(fileArray));
                    }
                    setFieldsValue({
                        templateTitle,
                        templateContent: BraftEditor.createEditorState(templateContent || ''),
                        resourceRelation: transformFileList(fileVOS)
                    });
                }
            }
        }
    );

    // 复制内容
    const handleCopy = () => {
        copy(
            `已为您生成专属【应聘通知】链接，您可以点击链接，实时查看最新应聘进度。
        链接：${templateData?.candidateLink}`
        );
        message.success('复制成功');
    };

    function showCopyConfirm() {
        confirm({
            title: '已通知候选人，您还可以复制【应聘通知】链接',
            content: '候选人可访问此链接，实时查看最新应聘进度',
            okText: '复制链接',
            okType: 'primary',
            centered: true,
            className: styles.copyBtn,
            width: 468,
            icon: <Icon type="exclamation-circle" theme="filled" color="#FFA22D" />,
            cancelText: '我知道了',
            onOk() {
                handleCopy();
            },
            onCancel() {
                // console.log('Cancel');
            }
        });
    }

    useEffect(() => {
        if (interviewArrangeDetail) {
            const { arrangeDetailVO, recruitInterviewHomeworkVO } = interviewArrangeDetail;
            setHomeWork(recruitInterviewHomeworkVO);
            const topicFileUrl = getPath(recruitInterviewHomeworkVO, 'topicFileUrl');
            if (topicFileUrl) {
                const fileArray = JSON.parse(topicFileUrl);
                setShowFileList(
                    fileArray.map(item => ({
                        uid: item.id,
                        name: item.name,
                        status: 'done',
                        url: item.url,
                        response: item.url
                    }))
                );
            }
            if (arrangeDetailVO) {
                const { interviewWay } = arrangeDetailVO;
                setInterviewWay(interviewWay);
            }
        }
    }, [templateList, interviewArrangeDetail]);

    React.useEffect(() => {
        let inUseList = templateList;
        if (interviewWay === 5) {
            inUseList = templateList?.filter(item => item.templateName.includes('作业'));
        }
        // if (isBackground) {
        //     inUseList = templateList?.filter(item => item.templateName.includes('背调')); // 裂开
        // }
        const defaultTpl = inUseList[0];
        if (!defaultTpl) return;
        setFieldsValue({
            templateId: defaultTpl.id,
            templateTitle: defaultTpl.templateTitle
        });
    }, [templateList, isBackground, interviewWay]);

    const sendMailApi = (() => {
        if (isBackground) {
            return sendEmailNoticeToThirdParty;
        }
        if (noticeType === NOTICE_TYPE.OFFER) {
            return sendHireEmail;
        }
        return sendEmailNotice;
    })();

    // 保存面试评估表
    const { loading: saveLoading, run: sendEmail } = useRequest(sendMailApi, {
        manual: true,
        onSuccess: res => {
            const { code, msg } = res;
            if (code === 10000) {
                // 弹出复制对话框，第三方背调不执行弹窗操作
                if (![NOTICE_TYPE.BACKGROUND].includes(noticeType)) {
                    showCopyConfirm();
                }
                message.success('通知成功');
                pageTabUtil.goBack(-Number(getPath(query, 'r', '0')) - 1);
                return;
            }
            if (code === 11000) {
                if (isBackground) {
                    message.error('请先前往【招聘设置-通知模板】配置通知发件邮箱，以便发送背调通知');
                } else if (noticeType === NOTICE_TYPE.OFFER) {
                    message.error('请先前往【招聘设置-通知模板】配置通知发件邮箱，以便发送录用通知');
                } else if (noticeType === NOTICE_TYPE.WEED_OUT) {
                    message.error('请先前往【招聘设置-通知模板】配置通知发件邮箱，以便发送淘汰通知');
                } else if (noticeType === NOTICE_TYPE.BACKGROUND) {
                    message.error('请先前往【招聘设置-通知模板】配置通知发件邮箱，以便发送背调通知');
                } else {
                    message.error('请先前往【招聘设置-通知模板】配置通知发件邮箱，以便发送面试通知');
                }

                return;
            }
            message.error(msg);
        }
    });

    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                const { templateContent, resourceRelation, ...rest } = values;
                const finalContent = templateContent.toHTML().replace(/a href/g, 'a style="color:#FFA22D" href');
                const finalParams = {
                    ...rest,
                    ...(contactId ? { contactId } : {}),
                    ...(employId ? { employId } : {}),
                    candidateId,
                    resourceRelation: resourceRelation?.uploadResourceFile
                        ? [resourceRelation?.uploadResourceFile]
                        : [],
                    templateContent: finalContent,
                    templateId: currentTemplateId
                };
                // 面试作业
                if (interviewWay === 5) {
                    const list = showFileList.filter(m => m.status !== 'error' && !m.isDefault);
                    const getTopFileUrl = () => {
                        if (list.length > 0) {
                            return JSON.stringify(
                                list.map(item => ({
                                    id: item.uid,
                                    url: item.response ? item.response : item.url,
                                    name: item.name
                                }))
                            );
                        }
                        return '';
                    };
                    const homeworkDTO = {
                        id: homeWork?.id,
                        topicFileUrl: getTopFileUrl()
                    };
                    try {
                        const result = await updateHomeWork(homeworkDTO);
                        sendEmail(finalParams);
                    } catch (error) {
                        message.error(error.message);
                    }
                } else {
                    const extraParam = isBackground ? { backgroundId } : {};
                    sendEmail({ ...finalParams, ...extraParam });
                }
            }
        });
    };

    // 不允许添加尺寸大于10M的文件
    const myValidateFn = file => {
        if (file.size > 1024 * 1024 * 10) {
            message.error('图片不能大于10M！');
            return false;
        }
        return true;
    };

    // 报错提示
    const handleEditorChange = editorState => {
        const html = editorState.toHTML();
        if (html.length > 20000) {
            message.error('邮件内容过多');
        }
    };

    const myUploadFn = param => {
        const onSuccess = (response, file) =>
            param.success({
                url: response.data[0].url,
                meta: {
                    id: file.name,
                    title: file.name,
                    alt: file.name
                }
            });
        customUpload({ files: param, onSuccess });
    };

    const controls = [
        'undo',
        'redo',
        'separator',
        'font-size',
        'line-height',
        'letter-spacing',
        'separator',
        'text-color',
        'bold',
        'italic',
        'underline',
        'strike-through',
        'separator',
        'superscript',
        'subscript',
        'remove-styles',
        'emoji',
        'separator',
        'text-indent',
        'text-align',
        'separator',
        'headings',
        'list-ul',
        'list-ol',
        'blockquote',
        'code',
        'separator',
        'media',
        'link',
        'hr',
        'separator',
        'clear'
    ];

    return (
        <PageHeaderWrapper>
            <Card
                title={isBackground ? '通知背调机构' : '通知候选人'}
                bordered={false}
                extra={
                    <BottomAction>
                        <Button
                            onClick={() => {
                                pageTabUtil.goBack(-Number(getPath(query, 'r', '0')) - 1);
                            }}
                        >
                            取消
                        </Button>
                        <Button type="primary" loading={saveLoading} onClick={handleSubmit}>
                            确定
                        </Button>
                    </BottomAction>
                }
            >
                <Form className={styles.formWrap} style={{ maxWidth: '100%' }}>
                    <Spin spinning={talentLoading}>
                        <div style={{ display: 'flex' }}>
                            <Form.Item
                                label={isBackground ? '背调机构邮箱' : '候选人邮箱'}
                                style={{ width: showUpdateTalentEmail ? '42%' : '50%' }}
                            >
                                {getFieldDecorator('toEmail', {
                                    initialValue: hasEmail ? email : getPath(talentInfo, 'talentEmail', ''),
                                    rules: [
                                        {
                                            required: true,
                                            message: '候选人邮箱不能为空'
                                        },
                                        {
                                            message: '请输入正确的邮箱',
                                            type: 'email'
                                        }
                                    ]
                                })(<Input placeholder="请输入候选人邮箱" allowClear maxLength={100} />)}
                            </Form.Item>
                            {noticeType !== NOTICE_TYPE.OFFER && (
                                <Form.Item style={{ marginLeft: 10 }}>
                                    {showUpdateTalentEmail &&
                                        getFieldDecorator('updateTalentEmailFlag', {
                                            initialValue: !talentInfo?.talentEmail,
                                            valuePropName: 'checked'
                                        })(
                                            <Checkbox disabled={!talentInfo?.talentEmail}>
                                                同步更新简历中的邮箱地址（邮箱是候选人登录 VV Work 的账号，请谨慎勾选）
                                            </Checkbox>
                                        )}
                                </Form.Item>
                            )}
                        </div>
                    </Spin>
                    <div style={{ display: 'flex' }}>
                        <Form.Item label="通知模版" style={{ width: '50%' }}>
                            <Spin spinning={templateLoading}>
                                {getFieldDecorator('templateId', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '通知模版不能为空'
                                        }
                                    ]
                                })(
                                    <Select
                                        placeholder="请选择通知模版"
                                        getPopupContainer={triggerNode => triggerNode.parentElement}
                                    >
                                        {templateList?.map(item => (
                                            <Option value={item.id} key={item.id}>
                                                {item.templateName}
                                            </Option>
                                        ))}
                                    </Select>
                                )}
                            </Spin>
                        </Form.Item>
                        <Form.Item label="邮件主题" style={{ width: '50%' }}>
                            <Spin spinning={loading}>
                                {getFieldDecorator('templateTitle', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '邮件主题不能为空'
                                        }
                                    ]
                                })(<Input placeholder="请输入邮件主题" allowClear maxLength={200} />)}
                            </Spin>
                        </Form.Item>
                    </div>
                    <Form.Item label="邮件内容">
                        <Spin spinning={loading}>
                            {getFieldDecorator('templateContent', {
                                initialValue: BraftEditor.createEditorState(null),
                                validateTrigger: 'onBlur',
                                rules: [
                                    {
                                        required: true,
                                        validator: (_, value, callback) => {
                                            if (value.isEmpty()) {
                                                callback('邮件内容不能为空');
                                            } else {
                                                callback();
                                            }
                                        },
                                        message: '邮件内容不能为空'
                                    }
                                ]
                            })(
                                <BraftEditor
                                    media={{
                                        uploadFn: myUploadFn,
                                        validateFn: myValidateFn,
                                        accepts: {
                                            image: 'image/png,image/jpeg,image/gif'
                                        }
                                    }}
                                    onChange={handleEditorChange}
                                    placeholder="请输入邮件内容"
                                    controls={controls}
                                    excludeControls={['fullscreen']}
                                    imageControls={[
                                        {
                                            onClick: block => {
                                                console.log(block);
                                            } // 指定控件点击后的回调，参数为当前图片的block对象
                                        },
                                        'align-left',
                                        'align-center',
                                        'align-right',
                                        'size',
                                        'remove'
                                    ]}
                                    contentStyle={{ height: 600 }}
                                />
                            )}
                        </Spin>
                    </Form.Item>
                    <Form.Item label="附件">
                        <Spin spinning={loading}>
                            {interviewWay !== 5 &&
                                getFieldDecorator('resourceRelation')(
                                    <FileUpload
                                        checkFileSizeMsg="文件大小不能超过10MB！"
                                        checkFileSize={10}
                                        categoryCode="RecruitMessageTemplateFile"
                                        checkFileType="DOC,DOCX,PDF,JPG,JPEG,rar,zip"
                                        checkFileTypeMsg="附件格式不合规，请确认！"
                                    >
                                        <Button
                                            disabled={form.getFieldValue('resourceRelation')?.allFileList?.length > 4}
                                            style={{ marginTop: 4, marginBottom: 4 }}
                                        >
                                            添加附件
                                        </Button>
                                        <div style={{ marginTop: 4 }}>
                                            支持 pdf、doc、docx、jpg、jpeg、rar、zip
                                            等格式的附件，单个文件大小为10MB以内
                                        </div>
                                    </FileUpload>
                                )}
                            {interviewWay === 5 && (
                                <UploadWork
                                    checkFileSize={50}
                                    checkFileType="rar、zip、pdf、jpg、doc、docx"
                                    fileList={showFileList}
                                    setFileList={changeAllFileList}
                                    checkFileTypeMsg="只能上传rar、zip、pdf、jpg、doc、docx格式的文件！"
                                    checkFileSizeMsg="文件大小不能超过50MB！"
                                    // onUploaded={onUploaded}
                                >
                                    <Button style={{ marginTop: 4, marginBottom: 4 }}>
                                        <AntdIcon type="upload" /> 添加附件
                                    </Button>
                                    <div style={{ marginTop: 4 }}>
                                        支持 rar、zip、pdf、jpg、doc、docx格式的附件，单个文件大小为50M以内
                                    </div>
                                </UploadWork>
                            )}
                        </Spin>
                    </Form.Item>
                </Form>
            </Card>
        </PageHeaderWrapper>
    );
};

export default Form.create({})(EmailNotice);
